<template>
    <div class="app-container">
        <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="200px"
            class="ruleForm"
            size="small"
        >
            <el-tag type="danger" class="tips"
                >请勿频繁操作，注意流量是否即将超限！！！</el-tag
            >

            <el-form-item label="设备编码" prop="equipCode">
                <el-input
                    readonly
                    v-model="ruleForm.equipCode"
                    placeholder="请点击搜索自动回显设备编码"
                    @change="codeChange"
                >
                    <el-button
                        slot="append"
                        icon="el-icon-search"
                        @click="isShowCodeData"
                    ></el-button
                ></el-input>
            </el-form-item>
            <el-form-item label="设备分类">
                <el-select
                    v-model="equipTypeCode"
                    disabled
                    placeholder="请选择设备分类"
                    @change="equipChange"
                >
                    <el-option
                        v-for="item in enums.EQUIP_CLASSIFY"
                        :key="item.code"
                        :label="item.label"
                        :value="item.code"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="日志类型" prop="logExtractParam.level">
                <el-select
                    @change="levelChange"
                    v-model="ruleForm.logExtractParam.level"
                    clearable
                    placeholder="请先选择日志类型"
                >
                    <el-option
                        v-for="item in logLevelOption"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="文件名称" prop="logExtractParam.filename">
                <el-input
                    clearable
                    v-model="ruleForm.logExtractParam.filename"
                    placeholder="请输入文件名称"
                ></el-input>
            </el-form-item>
            <el-form-item
                label="开始时间"
                required
                prop="logExtractParam.startTime"
            >
                <el-date-picker
                    type="date"
                    :append-to-body="false"
                    :popper-append-to-body="false"
                    :picker-options="begin"
                    @change="dateChange"
                    placeholder="请选择开始时间"
                    clearable
                    v-model="ruleForm.logExtractParam.startTime"
                    style="width: 100%"
                ></el-date-picker>
            </el-form-item>
            <el-form-item
                label="结束时间"
                required
                prop="logExtractParam.endTime"
            >
                <el-date-picker
                    type="date"
                    clearable
                    :append-to-body="false"
                    :popper-append-to-body="false"
                    :picker-options="process"
                    @change="dateChange"
                    placeholder="请选择开始时间"
                    v-model="ruleForm.logExtractParam.endTime"
                    style="width: 100%"
                ></el-date-picker>
            </el-form-item>
            <div class="tips ftptips">
                <el-link type="danger" :underline="false"
                    >注：若填写此项，则会根据所填内容创建目录；否则默认根目录
                    <br />可以用'/' 不能用'\',如：www/datas
                </el-link>
            </div>
            <el-form-item label="FTP目录">
                <el-input
                    clearable
                    v-model="ruleForm.logExtractParam.url"
                    placeholder="请输入FTP目录"
                    @keyup.native="keyUp"
                    @keydown.native="keydown"
                ></el-input>
            </el-form-item>
            <el-form-item label="接收日志邮箱" prop="receiveEmail">
                <el-input
                    clearable
                    v-model="ruleForm.receiveEmail"
                    placeholder="接收日志邮箱"
                ></el-input>
            </el-form-item>
            <el-form-item class="log_btns">
                <el-button @click="resetForm('ruleForm')" size="small"
                    >重置</el-button
                >
                <el-button
                    v-permission="['om:logextract:extract']"
                    type="primary"
                    size="small"
                    @click="submitForm('ruleForm')"
                    :loading="btnLoading"
                    >提取</el-button
                >
            </el-form-item>
        </el-form>

        <!-- 弹框 -->
        <Dialog
            class="equipChooseDialog"
            :visible="visible"
            width="48%"
            title="勾选需要日志提取的设备"
            @confirmDialog="confirmDialog"
            @cancelDialog="cancelDialog"
        >
            <el-form
                class="filters"
                ref="searchForm"
                :model="searchForm"
                label-width="70px"
            >
                <el-form-item label="设备编码">
                    <el-input
                        clearable
                        style="width: 100%"
                        v-model="searchForm.code"
                        placeholder="请点击搜索选择设备编码"
                    />
                </el-form-item>
                <el-form-item label="设备id">
                    <el-input
                        v-model="searchForm.id"
                        clearable
                        placeholder="请输入设备id"
                    />
                </el-form-item>
                <div class="search-btns">
                    <el-button
                        type="primary"
                        size="mini"
                        icon="el-icon-search"
                        @click="searchCodeData"
                        >搜索</el-button
                    >
                    <el-button
                        type="default"
                        size="mini"
                        icon="el-icon-refresh"
                        @click="clearData"
                        >重置</el-button
                    >
                </div>
            </el-form>
            <div class="table-box">
            <el-table
                :loading="codeListLoading"
                :data="equipCodeList"
                ref="tableDemand"
                style="width: 100%"
                stripe
            >
                <el-table-column
                    label="ID"
                    show-overflow-tooltip
                    prop="id"
                    min-width="40%"
                >
                    <template slot-scope="scope">
                        <el-radio
                            :disabled="!scope.row.isOnline"
                            :label="scope.row.id"
                            v-model="codeRadio"
                            @change.native="
                                handleSelectionChange(scope.$index, scope.row)
                            "
                            >&nbsp;</el-radio
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    prop="code"
                    label="设备编码"
                    min-width="40%"
                    show-overflow-tooltip
                ></el-table-column>

                <el-table-column
                    prop="isOnline"
                    label="是否在线"
                    min-width="15%"
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.isOnline ? 'success' : 'danger'"
                            >{{ onlineType(scope.row.isOnline) }}</el-tag
                        >
                    </template>
                </el-table-column>
            </el-table>
            </div>
            <pagination
                v-if="total > 0"
                :total="total"
                :pageSizes="[10, 20, 30, 40, 50]"
                :page.sync="searchForm.pageNum"
                :limit.sync="searchForm.pageSize"
                @pagination="searchCodeData"
            />
        </Dialog>
    </div>
</template>

<script>
import { logExtrace, logLevel } from "@/api/manage";
import moment from "moment";
import { equipment } from "@/api/factuer";
import { mapGetters } from "vuex";
import Dialog from "@/components/Dialog";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { removeNullUndefined } from "@/utils/index.js";
import { handleConfirm } from "@/utils/messageBox";

export default {
    components: { Dialog, Pagination },
    data() {
        return {
            ruleForm: {
                id: "",
                equipCode: "",
                equipClassify: "",
                receiveEmail: "",
                logExtractParam: {
                    startTime: "",
                    endTime: "",
                    level: "",
                    filename: "",
                    url: "",
                },
            },
            rules: {
                equipCode: [
                    {
                        required: true,
                        message: "请点击搜索选择设备编码",
                        trigger: "change",
                    },
                ],
                receiveEmail: [
                    {
                        required: true,
                        message: "请输入接收日志邮箱",
                        trigger: "blur",
                    },
                ],
                equipClassify: [
                    {
                        required: true,
                        message: "请选择设备分类",
                        trigger: "change",
                    },
                ],
                "logExtractParam.level": [
                    {
                        required: true,
                        message: "请选择日志类型",
                        trigger: "change",
                    },
                ],
                "logExtractParam.filename": [
                    {
                        required: true,
                        message: "请输入文件名称",
                        trigger: "change",
                    },
                ],
                "logExtractParam.startTime": [
                    {
                        required: true,
                        message: "请选择开始时间",
                        trigger: "blur",
                    },
                    {
                        required: true,
                        message: "请选择开始时间",
                        trigger: "change",
                    },
                ],
                "logExtractParam.endTime": [
                    {
                        required: true,
                        message: "请选择结束时间",
                        trigger: "blur",
                    },
                    {
                        required: true,
                        message: "请选择结束时间",
                        trigger: "change",
                    },
                ],
            },
            logLevelOption: [],
            btnLoading: false,
            fileType: "", //查询级别fileType

            equipCodeList: [], //搜索设备列表
            codeRadio: "",
            currentCodeItem: {}, //当前选中设备项

            visible: false, //弹框标识
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 10,
                code: null,
                id: null,
            },
            codeListLoading: false,
        };
    },

    computed: {
        ...mapGetters(["enums", "equipTypeCode"]),
        //日期时间选择控制，开始时间必须小于结束时间
        begin() {
            const _this = this;
            return {
                disabledDate(time) {
                    if (_this.ruleForm.logExtractParam.endTime) {
                        // 如果结束时间不为空，则只能小于结束时间
                        return (
                            new Date(
                                _this.ruleForm.logExtractParam.endTime
                            ).getTime() < time.getTime()
                        );
                    } else {
                        // 开始时间不选时，结束时间小于等于当天
                        return time.getTime() >= new Date().getTime();
                    }
                },
            };
        },
        process() {
            const _this = this;
            return {
                disabledDate(time) {
                    if (_this.ruleForm.logExtractParam.startTime) {
                        // 如果开始时间不为空，结束时间大于开始时间
                        let beginDateVal = new Date(
                            _this.ruleForm.logExtractParam.startTime
                        ).getTime();
                        return (
                            time.getTime() < beginDateVal ||
                            time.getTime() > Date.now()
                        ); //结束时间大于开始时间且小于当前时间
                    } else {
                        // 开始时间不选时，结束时间小于等于当天
                        return time.getTime() >= new Date().getTime();
                    }
                },
            };
        },
    },
    watch: {
        equipTypeCode: {
            handler(val) {
                this.equipChange(val);
            },
            immediate: true,
        },
    },
    methods: {
        //限制输入特殊字符
        keyUp(e) {
            e.target.value = e.target.value.replace(
                /[`~!@#$%^&*()_\-+=<>?:"{}|,.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                ""
            );
            this.ruleForm.logExtractParam.url = e.target.value;
        },
        // 只能输入汉字、英文、数字
        keydown(e) {
            e.target.value = e.target.value.replace(
                /[^\a-\z\A-\Z0-9\u4E00-\u9FA5/]/g,
                ""
            );
            this.ruleForm.logExtractParam.url = e.target.value;
        },
        async equipChange(e) {
            this.ruleForm.logExtractParam.level = "";
            this.logLevelOption = [];
            this.detalFile();
            let datas = await logLevel(`/all?equipClassify=${e}`, "post");
            this.logLevelOption = datas.data;
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    handleConfirm(`确定要提取日志吗？`, "warning", "提示")
                        .then((res) => {
                            this.doSubmit();
                        })
                        .catch((err) => {});
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        doSubmit() {
            this.btnLoading = true;
            let params = JSON.parse(JSON.stringify(this.ruleForm));
            params.logExtractParam.startTime = moment(
                params.logExtractParam.startTime
            )
                .startOf("day")
                .format("X");
            params.logExtractParam.endTime = moment(
                params.logExtractParam.endTime
            )
                .startOf("day")
                .format("X");
            params.id = this.currentCodeItem.id;
            params.equipClassify = this.equipTypeCode;
            delete params.equipCode;
            logExtrace("/insert", "post", params)
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success(res.message);
                        this.resetForm("ruleForm");
                    }
                })
                .finally(() => {
                    this.btnLoading = false;
                });
        },
        levelChange(e) {
            this.fileType = this.logLevelOption.find(
                (item) => item.code == e
            ).fileType;
            this.detalFile();
        },
        dateChange() {
            this.detalFile();
        },
        codeChange() {
            this.detalFile();
        },

        detalFile() {
            let startTime = this.ruleForm.logExtractParam.startTime
                ? moment(this.ruleForm.logExtractParam.startTime).format(
                      "YYYYMMDD"
                  )
                : "";
            let endTime = this.ruleForm.logExtractParam.endTime
                ? moment(this.ruleForm.logExtractParam.endTime).format(
                      "YYYYMMDD"
                  )
                : "";
            this.ruleForm.logExtractParam.filename = this.ruleForm
                .logExtractParam.startTime
                ? this.ruleForm.equipCode + "_" + startTime
                : this.ruleForm.equipCode;
            this.ruleForm.logExtractParam.filename += this.ruleForm
                .logExtractParam.endTime
                ? `_${endTime}`
                : "";
            this.ruleForm.logExtractParam.filename += this.ruleForm
                .logExtractParam.level
                ? `_${this.ruleForm.logExtractParam.level}${this.fileType}`
                : "";
        },
        isShowCodeData() {
            this.visible = true;
            this.searchCodeData();
        },
        searchCodeData() {
            this.equipCodeList = [];
            this.total = 0;
            this.codeListLoading = true;
            equipment(
                "/info/list",
                "post",
                {
                    ...removeNullUndefined(this.searchForm),
                },
                1
            )
                .then((res) => {
                    this.equipCodeList = res.data;
                    this.total = +res.total;
                })
                .finally(() => (this.codeListLoading = false));
        },

        onlineType(type) {
            let classify = this.enums.IS_ONLINE.find((p) => {
                return p.code == type;
            });
            return classify ? classify.label : "";
        },
        confirmDialog() {
            if (Object.keys(this.currentCodeItem).length == 0) {
                this.$message.error("请勾选需要日志提取的设备！");
                return;
            }
            this.visible = false;
            this.ruleForm.equipCode = this.currentCodeItem.code;
            this.codeChange();
        },
        cancelDialog() {
            this.visible = false;
            this.clearData();
        },
        clearData() {
            this.searchForm = {
                pageNum: this.searchForm.pageNum,
                pageSize: this.searchForm.pageSize,
                code: null,
                id: null,
            };
            this.codeRadio = "";
        },
        handleSelectionChange(index, row) {
            this.currentCodeItem = row;
        },
    },
};
</script>
<style scoped lang="scss">
.ruleForm {
    width: 40%;
    margin: 60px auto;
}
.el-select {
    width: 100%;
}
.log_btns {
    text-align: center;
    margin: 40px 0;
}
.tips {
    margin: 0 0 30px 22%;
    font-size: 18px;
}
.ftptips {
    margin-bottom: 10px;
}
.el-form-item {
    margin-bottom: 18px;
}

.filters .el-form-item {
    margin-bottom: 0;
    width: 34%;
}
.equipChooseDialog {
    .pagination-container {
        padding: 10px 0 0;
    }
}
::v-deep .el-input.is-disabled .el-input__inner {
    color: #333;
}
</style>
